﻿using Microsoft.Extensions.Logging;
using Quartz;
using SimulationCenter.Schedulers;
using SimulationCenter.Tasks.Svrs;
using System;
using System.Threading.Tasks;

namespace SimulationCenter.Jobs
{
    /// <summary>
    /// 任务恢复
    /// </summary>
    [DisallowConcurrentExecution]
    public class ScStartUpJob : IJob
    {
        private readonly ITaskSvr _taskSvr;
        private readonly ScScheduleManager _scheduleManager;
        private readonly AdbCenter _adbCenter;
        private readonly ILogger<ScStartUpJob> _logger;

        public ScStartUpJob(ITaskSvr taskSvr, ScScheduleManager scheduleManager, AdbCenter adbCenter, ILogger<ScStartUpJob> logger)
        {
            _taskSvr = taskSvr;
            _scheduleManager = scheduleManager;
            _adbCenter = adbCenter;
            _logger = logger;
        }

        public async Task Execute(IJobExecutionContext context)
        {
            try
            {
                var devices = _adbCenter.GetDeviceSerials();

                _logger.LogInformation($"connected devices: {string.Join(",", devices.ToArray())}");

                await _taskSvr.AddStartUpTasks(devices);

                var scTasks = await _taskSvr.GetRecoveryTasks();

                foreach (var scTask in scTasks)
                {
                    await _scheduleManager.AddScTaskSchedule(scTask);
                }
            }
            catch (Exception e)
            {
                _logger.LogError(e, "executed startup job");
            }
        }
    }
}
